﻿package net.oschina.cordova.sharesdk;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;


@SuppressLint({ "SimpleDateFormat", "HandlerLeak" })
public class DownLoadPic {
	
	private Context mContext;
	

	private String downurl;
	ProgressDialog pd = null;
	
	
	
	public void downFile(Context montext ,String url) {
		this.mContext=montext;
		this.downurl=url;
		pd = new ProgressDialog(mContext);
		pd.setTitle("正在下载");
		pd.setMessage("请稍后。。。");
		pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);

		final String ss = downurl.trim();

		pd.show();
		new Thread() {
		
			@SuppressWarnings("unused")
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(ss);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						// 获取扩展SD卡设备状态
						 String sDStateString =
						 android.os.Environment.getExternalStorageState();
						 if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)||
						 sDStateString.endsWith(android.os.Environment.MEDIA_MOUNTED_READ_ONLY)
						 )
						 {
						 String path = Environment.getExternalStorageDirectory().getPath() ;
				
						
						
						File ff=new File(Environment.getExternalStorageDirectory()
										+ "/OSchinaPic/");
						
						if(!ff.exists()){
							
							ff.mkdirs();
						}
						
			            SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMdd" 
			                    + "hhmmss");  

			             int le=downurl.split("/").length;
			            
			            System.out.println(le);
			            
			            
			            String datetime=downurl.split("/")[le-1];

						File file = new File(
							ff,datetime);
						if(file.exists()){
							System.out.println("delete---file");
							file.delete();}

						
						
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {

							fileOutputStream.write(buf, 0, ch);
							count += ch;
							if (length > 0) {
							}
						}
						
						 
						 }else{
							
							down("failed");
							
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					down("sucess");
				} catch (ClientProtocolException e) {
					down("failed");
					e.printStackTrace();
				} catch (IOException e) {
					down("failed");
					e.printStackTrace();
				}
			}
		}.start();
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			super.handleMessage(msg);

		
			pd.cancel();
		
			if(msg.obj.toString().equals("sucess")){
	
//				   Intent intent = getPdfFileIntent("/mnt/sdcard/Tian/t0.pdf"); 
//
//				   mContext.startActivity(intent);
				Toast.makeText(mContext, "下载完成!",
						Toast.LENGTH_SHORT).show();}
			
			
			
				else{
					
					Toast.makeText(mContext, "下载失败!",
							Toast.LENGTH_SHORT).show();
					}
		}
	};

	/**
	 * 下载完成，通过handler将下载对话框取消
	 */
	public void down(final String iss) {
		new Thread() {
			public void run() {
				Message message = handler.obtainMessage();
				message.obj=iss;
				handler.sendMessage(message);
			}
		}.start();
	}
	/**

	    * Get PDF file Intent 打开PDF文件

	    */ 

//	   public Intent getPdfFileIntent(String path){ 
//
//	    Intent i = new Intent(Intent.ACTION_VIEW); 
//
//	    i.addCategory(Intent.CATEGORY_DEFAULT); 
//
//	    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK ); 
//
//	    Uri uri = Uri.fromFile(new File(path)); 
//
//	    i.setDataAndType(uri, "application/pdf"); 
//
//	    return i; 

//	} 

}
